import copy
from flask import Flask, render_template, jsonify
import os, json
import coordtransform

current_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(current_dir)
grandpa_dir = os.path.dirname(parent_dir)
print("current dir:", current_dir)

app = Flask(
    __name__,
    static_folder=parent_dir + "/static",
    template_folder=parent_dir + "/static"
    )

It = 0
ships = {}
with open("test/server/ship_slice.json", "r", encoding="utf-8") as f:
    ships = json.load(f)

@app.route("/")
def index():
    return render_template("traffic_flow_rt.html")

@app.route("/data/slice")
def slice():
    global It, ships
    # print("It:  ", It)
    ship_modified = []
    for ship in ships[It]:
        new_ship = copy.deepcopy(ship)
        new_ship["LON"], new_ship["LAT"] = coordtransform.wgs84tobd09(ship.get("LON"), ship.get("LAT"))
        ship_modified.append(new_ship)
    
    It += 1
    if It >= 277:
        It = 0
    return jsonify(ship_modified)

@app.route("/data/test")
def test():
    with open("test/server/ship_slice.json", "r", encoding="utf-8") as f:
        data = json.load(f)
    ship_modified = []
    for ship in data[0]:
        LON, LAT = coordtransform.wgs84tobd09(ship.get("LON"), ship.get("LAT"))
        ship["LON"], ship["LAT"] = LON, LAT
        ship_modified.append(ship)
    return jsonify(ship_modified)

if __name__ == "__main__":
    app.run(debug=True)